<template>
  <div class="scientific-calculator-tool">
    <div class="tool-header">
      <h1>科学计算器</h1>
      <p>功能强大的科学计算器，支持基本运算和科学函数</p>
    </div>

    <div class="tool-container">
      <el-row :gutter="20">
        <!-- 计算器界面 -->
        <el-col :span="16">
          <div class="calculator-section">
            <div class="calculator-display">
              <div class="display-input">{{ displayInput }}</div>
              <div class="display-result">{{ displayResult }}</div>
            </div>
            
            <div class="calculator-buttons">
              <!-- 第一行：清除和功能键 -->
              <div class="button-row">
                <el-button @click="clearAll" class="calc-btn function-btn">C</el-button>
                <el-button @click="clearEntry" class="calc-btn function-btn">CE</el-button>
                <el-button @click="backspace" class="calc-btn function-btn">⌫</el-button>
                <el-button @click="inputOperator('/')" class="calc-btn operator-btn">÷</el-button>
              </div>
              
              <!-- 第二行：数字和运算符 -->
              <div class="button-row">
                <el-button @click="inputNumber('7')" class="calc-btn number-btn">7</el-button>
                <el-button @click="inputNumber('8')" class="calc-btn number-btn">8</el-button>
                <el-button @click="inputNumber('9')" class="calc-btn number-btn">9</el-button>
                <el-button @click="inputOperator('*')" class="calc-btn operator-btn">×</el-button>
              </div>
              
              <!-- 第三行：数字和运算符 -->
              <div class="button-row">
                <el-button @click="inputNumber('4')" class="calc-btn number-btn">4</el-button>
                <el-button @click="inputNumber('5')" class="calc-btn number-btn">5</el-button>
                <el-button @click="inputNumber('6')" class="calc-btn number-btn">6</el-button>
                <el-button @click="inputOperator('-')" class="calc-btn operator-btn">-</el-button>
              </div>
              
              <!-- 第四行：数字和运算符 -->
              <div class="button-row">
                <el-button @click="inputNumber('1')" class="calc-btn number-btn">1</el-button>
                <el-button @click="inputNumber('2')" class="calc-btn number-btn">2</el-button>
                <el-button @click="inputNumber('3')" class="calc-btn number-btn">3</el-button>
                <el-button @click="inputOperator('+')" class="calc-btn operator-btn">+</el-button>
              </div>
              
              <!-- 第五行：0、小数点和等号 -->
              <div class="button-row">
                <el-button @click="inputNumber('0')" class="calc-btn number-btn zero-btn">0</el-button>
                <el-button @click="inputDecimal" class="calc-btn number-btn">.</el-button>
                <el-button @click="calculate" class="calc-btn equals-btn">=</el-button>
              </div>
            </div>
            
            <!-- 科学函数按钮 -->
            <div class="scientific-functions">
              <h4>科学函数</h4>
              <div class="function-grid">
                <el-button @click="inputFunction('sqrt')" class="calc-btn function-btn">√</el-button>
                <el-button @click="inputFunction('pow')" class="calc-btn function-btn">x²</el-button>
                <el-button @click="inputFunction('sin')" class="calc-btn function-btn">sin</el-button>
                <el-button @click="inputFunction('cos')" class="calc-btn function-btn">cos</el-button>
                <el-button @click="inputFunction('tan')" class="calc-btn function-btn">tan</el-button>
                <el-button @click="inputFunction('log')" class="calc-btn function-btn">log</el-button>
                <el-button @click="inputFunction('ln')" class="calc-btn function-btn">ln</el-button>
                <el-button @click="inputFunction('pi')" class="calc-btn function-btn">π</el-button>
                <el-button @click="inputFunction('e')" class="calc-btn function-btn">e</el-button>
                <el-button @click="inputFunction('factorial')" class="calc-btn function-btn">n!</el-button>
              </div>
            </div>
          </div>
        </el-col>

        <!-- 计算历史和说明 -->
        <el-col :span="8">
          <div class="history-section">
            <div class="section-header">
              <h3>计算历史</h3>
              <el-button @click="clearHistory" size="small" type="danger">清空</el-button>
            </div>
            
            <div class="history-list">
              <div 
                v-for="(item, index) in history" 
                :key="index"
                class="history-item"
                @click="loadFromHistory(item)"
              >
                <div class="history-expression">{{ item.expression }}</div>
                <div class="history-result">= {{ item.result }}</div>
              </div>
              <div v-if="history.length === 0" class="empty-history">
                暂无计算历史
              </div>
            </div>
          </div>
          
          <div class="help-section">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>使用说明</span>
                </div>
              </template>
              
              <div class="help-content">
                <h4>基本操作：</h4>
                <ul>
                  <li><strong>C:</strong> 清除所有</li>
                  <li><strong>CE:</strong> 清除当前输入</li>
                  <li><strong>⌫:</strong> 退格删除</li>
                  <li><strong>=:</strong> 计算结果</li>
                </ul>
                
                <h4>科学函数：</h4>
                <ul>
                  <li><strong>√:</strong> 平方根</li>
                  <li><strong>x²:</strong> 平方</li>
                  <li><strong>sin/cos/tan:</strong> 三角函数</li>
                  <li><strong>log:</strong> 常用对数</li>
                  <li><strong>ln:</strong> 自然对数</li>
                  <li><strong>π:</strong> 圆周率</li>
                  <li><strong>e:</strong> 自然常数</li>
                  <li><strong>n!:</strong> 阶乘</li>
                </ul>
                
                <h4>注意事项：</h4>
                <div class="warning">
                  <p>⚠️ 三角函数使用弧度制</p>
                  <p>⚠️ 阶乘仅支持正整数</p>
                  <p>⚠️ 负数开方会显示错误</p>
                </div>
              </div>
            </el-card>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'

const displayInput = ref('')
const displayResult = ref('0')
const history = ref([])
const currentExpression = ref('')
const lastResult = ref(null)
const waitingForOperand = ref(false)

const inputNumber = (num) => {
  if (waitingForOperand.value) {
    displayInput.value = num
    waitingForOperand.value = false
  } else {
    displayInput.value = displayInput.value === '0' ? num : displayInput.value + num
  }
}

const inputDecimal = () => {
  if (waitingForOperand.value) {
    displayInput.value = '0.'
    waitingForOperand.value = false
  } else if (displayInput.value.indexOf('.') === -1) {
    displayInput.value += '.'
  }
}

const inputOperator = (op) => {
  const inputValue = parseFloat(displayInput.value)
  
  if (lastResult.value !== null && !waitingForOperand.value) {
    currentExpression.value = lastResult.value + ' ' + op + ' '
  } else {
    currentExpression.value = displayInput.value + ' ' + op + ' '
  }
  
  lastResult.value = inputValue
  waitingForOperand.value = true
}

const inputFunction = (func) => {
  const inputValue = parseFloat(displayInput.value)
  let result
  
  try {
    switch (func) {
      case 'sqrt':
        if (inputValue < 0) throw new Error('负数不能开方')
        result = Math.sqrt(inputValue)
        break
      case 'pow':
        result = Math.pow(inputValue, 2)
        break
      case 'sin':
        result = Math.sin(inputValue)
        break
      case 'cos':
        result = Math.cos(inputValue)
        break
      case 'tan':
        result = Math.tan(inputValue)
        break
      case 'log':
        if (inputValue <= 0) throw new Error('对数函数定义域错误')
        result = Math.log10(inputValue)
        break
      case 'ln':
        if (inputValue <= 0) throw new Error('对数函数定义域错误')
        result = Math.log(inputValue)
        break
      case 'pi':
        result = Math.PI
        break
      case 'e':
        result = Math.E
        break
      case 'factorial':
        if (inputValue < 0 || !Number.isInteger(inputValue)) {
          throw new Error('阶乘仅支持非负整数')
        }
        result = factorial(inputValue)
        break
    }
    
    displayResult.value = formatNumber(result)
    displayInput.value = result.toString()
    waitingForOperand.value = true
    
    // 添加到历史
    addToHistory(`${func}(${inputValue})`, result)
    
  } catch (error) {
    ElMessage.error(error.message)
  }
}

const factorial = (n) => {
  if (n === 0 || n === 1) return 1
  let result = 1
  for (let i = 2; i <= n; i++) {
    result *= i
  }
  return result
}

const calculate = () => {
  try {
    if (currentExpression.value && !waitingForOperand.value) {
      const expression = currentExpression.value + displayInput.value
      const result = evaluateExpression(expression)
      
      displayResult.value = formatNumber(result)
      displayInput.value = result.toString()
      
      // 添加到历史
      addToHistory(expression, result)
      
      currentExpression.value = ''
      lastResult.value = result
      waitingForOperand.value = true
    }
  } catch (error) {
    ElMessage.error('计算错误：' + error.message)
  }
}

const evaluateExpression = (expression) => {
  // 简单的表达式求值（实际项目中建议使用更安全的解析器）
  const cleanExpression = expression.replace(/×/g, '*').replace(/÷/g, '/')
  return Function('"use strict"; return (' + cleanExpression + ')')()
}

const formatNumber = (num) => {
  if (Number.isInteger(num)) {
    return num.toString()
  }
  return parseFloat(num.toFixed(10)).toString()
}

const addToHistory = (expression, result) => {
  history.value.unshift({
    expression: expression,
    result: formatNumber(result)
  })
  
  // 限制历史记录数量
  if (history.value.length > 50) {
    history.value = history.value.slice(0, 50)
  }
}

const loadFromHistory = (item) => {
  displayInput.value = item.result
  displayResult.value = item.result
  currentExpression.value = ''
  lastResult.value = parseFloat(item.result)
  waitingForOperand.value = true
}

const clearAll = () => {
  displayInput.value = ''
  displayResult.value = '0'
  currentExpression.value = ''
  lastResult.value = null
  waitingForOperand.value = false
}

const clearEntry = () => {
  displayInput.value = ''
}

const backspace = () => {
  if (displayInput.value.length > 0) {
    displayInput.value = displayInput.value.slice(0, -1)
  }
}

const clearHistory = () => {
  history.value = []
  ElMessage.success('历史记录已清空')
}
</script>

<style scoped>
.scientific-calculator-tool {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.tool-header {
  text-align: center;
  margin-bottom: 40px;
}

.tool-header h1 {
  font-size: 2.5rem;
  color: #333;
  margin-bottom: 10px;
}

.tool-header p {
  color: #666;
  font-size: 1.1rem;
}

.tool-container {
  margin-bottom: 40px;
}

.calculator-section,
.history-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
  height: 100%;
}

.calculator-display {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  border: 2px solid #e9ecef;
}

.display-input {
  font-size: 1.2rem;
  color: #666;
  min-height: 24px;
  text-align: right;
}

.display-result {
  font-size: 2rem;
  font-weight: bold;
  color: #333;
  text-align: right;
  min-height: 40px;
}

.calculator-buttons {
  margin-bottom: 30px;
}

.button-row {
  display: flex;
  gap: 8px;
  margin-bottom: 8px;
}

.calc-btn {
  flex: 1;
  height: 60px;
  font-size: 1.2rem;
  font-weight: bold;
  border-radius: 8px;
  border: none;
  transition: all 0.2s ease;
}

.number-btn {
  background: #f8f9fa;
  color: #333;
}

.number-btn:hover {
  background: #e9ecef;
  transform: translateY(-2px);
}

.operator-btn {
  background: #667eea;
  color: white;
}

.operator-btn:hover {
  background: #5a6fd8;
  transform: translateY(-2px);
}

.function-btn {
  background: #6c757d;
  color: white;
}

.function-btn:hover {
  background: #5a6268;
  transform: translateY(-2px);
}

.equals-btn {
  background: #28a745;
  color: white;
}

.equals-btn:hover {
  background: #218838;
  transform: translateY(-2px);
}

.zero-btn {
  flex: 2;
}

.scientific-functions {
  margin-top: 20px;
}

.scientific-functions h4 {
  color: #333;
  margin-bottom: 15px;
  font-size: 1.1rem;
}

.function-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 8px;
}

.function-grid .calc-btn {
  height: 50px;
  font-size: 1rem;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  color: #333;
  margin: 0;
  font-size: 1.3rem;
}

.history-list {
  max-height: 300px;
  overflow-y: auto;
}

.history-item {
  padding: 12px;
  border-radius: 8px;
  margin-bottom: 8px;
  background: #f8f9fa;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid #e9ecef;
}

.history-item:hover {
  background: #e9ecef;
  transform: translateY(-1px);
}

.history-expression {
  font-size: 0.9rem;
  color: #666;
  margin-bottom: 4px;
}

.history-result {
  font-size: 1.1rem;
  font-weight: bold;
  color: #333;
}

.empty-history {
  text-align: center;
  color: #999;
  padding: 40px 0;
  font-style: italic;
}

.help-section {
  margin-top: 20px;
}

.card-header {
  font-weight: bold;
  color: #333;
}

.help-content h4 {
  color: #333;
  margin: 20px 0 10px 0;
  font-size: 1.1rem;
}

.help-content ul {
  color: #666;
  padding-left: 20px;
  margin-bottom: 15px;
}

.help-content li {
  margin-bottom: 5px;
}

.warning {
  background: #fff3cd;
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid #ffc107;
  margin: 15px 0;
}

.warning p {
  margin: 5px 0;
  color: #856404;
}

@media (max-width: 768px) {
  .tool-header h1 {
    font-size: 2rem;
  }
  
  .calculator-buttons {
    margin-bottom: 20px;
  }
  
  .calc-btn {
    height: 50px;
    font-size: 1rem;
  }
  
  .function-grid {
    grid-template-columns: repeat(3, 1fr);
  }
  
  .history-item {
    padding: 8px;
  }
}
</style>
